﻿using JinYuan.Helper;
using JinYuan.Models;
using JinYuan.VirtualDataLibrary;
using Language;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Windows.Forms;

namespace LargeSquareOne
{
    public partial class FrmUserManage : MultiLanguageForm
    {
        public FrmUserManage()
        {
            InitializeComponent();
            this.dgv_Main.AutoGenerateColumns = false;
            UpdateSysAdminList();
            if (sysAdmins.Count > 0)
            {
                UpdateSysAdminInfo(sysAdmins[0]);
            }
        }

        /// <summary>
        /// 当前用户中所有的用户集合
        /// </summary>
        private List<SysAdmin> sysAdmins = new List<SysAdmin>();
        /// <summary>
        /// 更新用户集合
        /// </summary>
        private void UpdateSysAdminList()
        {
            try
            {
                sysAdmins = CommonMethods.db.QueryDataTable(CommonMethods.dBSQL.GetSysAdminSql()).ToDataList<SysAdmin>();
                sysAdmins.ForEach(c => c.LoginPwd = StringSecurityHelper.DESDecrypt(c.LoginPwd));
                this.dgv_Main.DataSource = null;
                this.dgv_Main.DataSource = sysAdmins;

            }
            catch (Exception ex)
            {
                new FrmMsgBoxWithAck("查询失败：".Translated() + ex.Message, "用户查询失败".Translated()).ShowDialog();
            }
        }

        private void UpdateSysAdminInfo(SysAdmin sysAdmin)
        {
            this.txt_LoginName.Text = sysAdmin.LoginName;
            this.txtICCard.Text = sysAdmin.LoginUid;
            this.txt_LoginPwd.Text = sysAdmin.LoginPwd;
            this.txt_LoginPwd2.Text = sysAdmin.LoginPwd;
            this.cmbUserLevel.Text = sysAdmin.LoginLevel;
            this.chk_SystemLog.Checked = sysAdmin.SystemLog;
            this.chk_CPK.Checked = sysAdmin.CpkData;
            this.chk_HistorySelect.Checked = sysAdmin.HistoryData;
            this.chk_SystemSet.Checked = sysAdmin.SystemSet;
            this.chk_Paramset.Checked = sysAdmin.ParamSet;
            this.chk_UserManage.Checked = sysAdmin.UserManage;
        }

        private void FrmUserManage_Load(object sender, EventArgs e)
        {
        }

        private void cmbUserLevel_SelectedIndexChanged(object sender, EventArgs e)
        {
            CommonMethods.mesConfig.userLevel = cmbUserLevel.Text.ToString();
        }

        private void dgv_Main_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                int i = this.dgv_Main.SelectedRows[0].Index;
                UpdateSysAdminInfo(sysAdmins[this.dgv_Main.SelectedRows[0].Index]);
            }
        }

        private void dgv_Main_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            //显示序列号
            DataGridViewHelper.DgvRowPostPaint(this.dgv_Main, e);
        }

        private void dgv_Main_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.RowIndex >= 0 && e.ColumnIndex > 2)
            {
                string value = this.dgv_Main.Rows[e.RowIndex].Cells[e.ColumnIndex].Value?.ToString();
                if (value == "True")
                {
                    e.Value = "启用";
                }
                else
                {
                    e.Value = "禁用";
                }
            }
        }

        private void btn_Add_Click(object sender, EventArgs e)
        {
            //数据验证
            if (this.txt_LoginName.Text.Length == 0)
            {
                new FrmMsgBoxWithAck("用户名不能为空", "添加用户").ShowDialog();
                return;
            }
            if (this.txt_LoginPwd.Text.Length == 0)
            {
                new FrmMsgBoxWithAck("用户密码不能为空", "添加用户").ShowDialog();
                return;
            }
            if (this.txt_LoginPwd2.Text.Length == 0)
            {
                new FrmMsgBoxWithAck("确认密码不能为空", "添加用户").ShowDialog();
                return;
            }
            if (this.txt_LoginPwd.Text != this.txt_LoginPwd2.Text)
            {
                new FrmMsgBoxWithAck("两次输入密码不一致", "添加用户").ShowDialog();
                return;
            }
            if (sysAdmins.Where(c => c.LoginName == this.txt_LoginName.Text.Trim()).ToList().Count > 0)
            {
                new FrmMsgBoxWithAck("该用户名已经存在", "添加用户").ShowDialog();
                return;
            }
            //封装数据
            SysAdmin sysAdmin = new SysAdmin()
            {
                LoginName = this.txt_LoginName.Text.Trim(),
                LoginPwd = StringSecurityHelper.DESEncrypt(this.txt_LoginPwd.Text.Trim()),
                LoginUid = this.txtICCard.Text.Trim(),
                LoginLevel = CommonMethods.mesConfig.userLevel,
                SystemLog = this.chk_SystemLog.Checked,
                CpkData = this.chk_CPK.Checked,
                HistoryData = this.chk_HistorySelect.Checked,
                ParamSet = this.chk_Paramset.Checked,
                SystemSet = this.chk_SystemSet.Checked,
                UserManage = this.chk_UserManage.Checked
            };

            //调用方法
            try
            {
                if (CommonMethods.db.AddReturnBool(sysAdmin))
                {
                    UpdateSysAdminList();
                }
                else
                {
                    new FrmMsgBoxWithAck("添加用户失败", "添加用户").ShowDialog();

                }
            }
            catch (Exception ex)
            {
                new FrmMsgBoxWithAck("添加用户失败:" + ex.Message, "添加用户").ShowDialog();
            }
        }

        private void btn_Modify_Click(object sender, EventArgs e)
        {
            //数据验证
            if (this.txt_LoginName.Text.Length == 0)
            {
                new FrmMsgBoxWithAck("用户名不能为空", "修改用户").ShowDialog();
                return;
            }
            if (this.txt_LoginPwd.Text.Length == 0)
            {
                new FrmMsgBoxWithAck("用户密码不能为空", "修改用户").ShowDialog();
                return;
            }
            if (this.txt_LoginPwd2.Text.Length == 0)
            {
                new FrmMsgBoxWithAck("确认密码不能为空", "修改用户").ShowDialog();
                return;
            }
            if (this.txt_LoginPwd.Text != this.txt_LoginPwd2.Text)
            {
                new FrmMsgBoxWithAck("两次输入密码不一致", "修改用户").ShowDialog();
                return;
            }
            //如果修改用户名就需要进行判断用户名是否存在
            //if (sysAdmins[this.dgv_Main.SelectedRows[0].Index].LoginName != this.txt_LoginName.Text)
            //{
            //    if (sysAdmins.Where(c => c.LoginName == this.txt_LoginName.Text.Trim()).ToList().Count > 0)
            //    {
            //        new FrmMsgBoxWithAck("该用户名已经存在", "修改用户").ShowDialog();
            //        return;
            //    }
            //}

            //封装数据
            SysAdmin sysAdmin = new SysAdmin()
            {
                LoginId = sysAdmins[this.dgv_Main.SelectedRows[0].Index].LoginId,
                LoginName = this.txt_LoginName.Text.Trim(),
                LoginPwd = StringSecurityHelper.DESEncrypt(this.txt_LoginPwd.Text.Trim()),
                LoginUid = this.txtICCard.Text.Trim(),
                LoginLevel = CommonMethods.mesConfig.userLevel,
                SystemLog = this.chk_SystemLog.Checked,
                CpkData = this.chk_CPK.Checked,
                HistoryData = this.chk_HistorySelect.Checked,
                SystemSet = this.chk_SystemSet.Checked,
                ParamSet = this.chk_Paramset.Checked,
                UserManage = this.chk_UserManage.Checked
            };

            //调用方法
            try
            {
                if (CommonMethods.db.Update<SysAdmin>(sysAdmin, it => it.LoginId == sysAdmin.LoginId) == 1)
                {
                    UpdateSysAdminList();
                }
                else
                {
                    new FrmMsgBoxWithAck("修改用户失败", "修改用户").ShowDialog();
                }
            }
            catch (Exception ex)
            {
                new FrmMsgBoxWithAck("修改用户失败:" + ex.Message, "修改用户").ShowDialog();
            }
        }



        private void btn_Delete_Click(object sender, EventArgs e)
        {
            int loginId = sysAdmins[this.dgv_Main.SelectedRows[0].Index].LoginId;
            string loginName = sysAdmins[this.dgv_Main.SelectedRows[0].Index].LoginName;
            try
            {
                if (new FrmMsgBoxWithAck($"是否删除{loginName}用户！", "删除提示").ShowDialog() == DialogResult.OK)
                {
                    if (CommonMethods.db.Delete<SysAdmin>(it => it.LoginId == loginId) == 1)
                    {
                        UpdateSysAdminList();
                    }
                    else
                    {
                        new FrmMsgBoxWithAck("删除用户失败", "修改用户").ShowDialog();
                    }
                }
            }
            catch (Exception ex)
            {

                new FrmMsgBoxWithAck("删除用户失败:" + ex.Message, "修改用户").ShowDialog();
            }
        }

        private void btn_Clear_Click(object sender, EventArgs e)
        {
            this.txt_LoginName.Clear();
            this.txtICCard.Clear();
            this.txt_LoginPwd.Clear();
            this.txt_LoginPwd2.Clear();
            SetChecked(false);
        }

        private void btn_SelectAll_Click(object sender, EventArgs e)
        {
            SetChecked(!this.chk_SystemSet.Checked);
        }

        private void SetChecked(bool value)
        {
            this.chk_SystemLog.Checked = value;
            this.chk_CPK.Checked = value;
            this.chk_HistorySelect.Checked = value;
            this.chk_SystemSet.Checked = value;
            this.chk_Paramset.Checked = value;
            this.chk_UserManage.Checked = value;
        }


        #region 减少闪烁
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams parss = base.CreateParams;
                parss.ExStyle |= 0x02000000;
                return parss;
            }
        }




        #endregion

        private void txtICCard_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Control && e.KeyCode == Keys.V)
            {
                e.Handled = true;
            }
        }

        DateTime dt1;
        DateTime dt2;
        private void txtICCard_KeyUp(object sender, KeyEventArgs e)
        {
            string Item = txtICCard.Text.Trim();
            if (txtICCard.TextLength == 1)
            {
                dt1 = System.DateTime.Now;
            }
            if (txtICCard.TextLength == 2)
            {
                dt2 = System.DateTime.Now;
                TimeSpan _ts = dt2.Subtract(dt1);
                if (_ts.Milliseconds > 50)
                {
                    new FrmMsgBoxWithAck("禁止手动输入，请使用厂牌扫描录入", "IC卡号").ShowDialog();
                    txtICCard.Clear();
                }
            }
        }
    }
}
